home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 3863 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  2.0 KB

  1. Path: dawn.mmm.com!news
  2. From: kjhopps@mmm.com (Kevin J Hopps)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Constructors and exceptions
  5. Date: 26 Jan 1996 13:13:54 GMT
  6. Organization: 3M - St. Paul, MN  55144-1000 US
  7. Message-ID: <4eak2i$hgq@dawn.mmm.com>
  8. References: <3107A899.4A86@tribeca.ios.com>
  9. Reply-To: kjhopps@mmm.com
  10. X-Newsreader: TIN [version 1.2 PL2]
  11.  
  12. John Leonard (leonardj@tribeca.ios.com) wrote:
  13. > Let's say that you have a class, we'll call it WindowClass, which, when it is constructed, 
  14. > opens a file, allocates memory for the file, reads the file into memory, and then opens a window. 
  15. > Let's say furthermore that you are going to create the object with a call to 'new' like this:
  16.  
  17. >      WindowClass     *aWC = new WindowClass(filename);
  18.  
  19. >      Now let's say that during initialization of the object, after it allocates the memory it finds 
  20. > that it cannot open the window. At this point I suppose it would be necessary to de-allocate the 
  21. > memory that had been allocated and close the file, then throw an exception. Now as far as I can tell 
  22. > when you use 'new' like this to allocate and initialize an object two things must happen: 
  23. > first, space must be reserved by the 'new' function for the objects data members, then, the 
  24. > constructor is called. If this process aborts after the memory has been allocated how can the 
  25. > application free it?
  26. >      Thanks,
  27. >      John Leonard
  28.  
  29. You are correct.  The resources acquired by the constructor must be
  30. released by the constructor.  If the constructor throws an exception,
  31. the [memory] resources acquired by new will be released for you.  (If
  32. the compiler adheres to the standard.)
  33. --
  34. Kevin J. Hopps                  e-mail: kjhopps@mmm.com
  35. 3M Company                      phone:  (612) 737-4643
  36. 3M Center, Bldg. 235-2D-57      fax:    (612) 737-2700
  37. St. Paul, MN 55144-1000         Opinions are my own.  I don't speak for 3M.
  38.     But 3M speaks for me -- I did not write the following line:
  39.  
  40. Opinions expressed herein are my own and may not represent those of 3M.
  41.